package cn.cqvie.controller;

import cn.cqvie.common.R;
import cn.cqvie.dto.OrderDto;
import cn.cqvie.pojo.AddressBook;
import cn.cqvie.pojo.OrderDetail;
import cn.cqvie.pojo.Orders;
import cn.cqvie.pojo.User;
import cn.cqvie.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    private OrdersService orderService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;

    @GetMapping("/getMSG")
    public R<Page> getOrders(int page,int pageSize,String username){
        Page<Orders> myPage=new Page<>(page,pageSize);
        Page<OrderDto> dtoPage=new Page<>();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(username), Orders::getUsername,username);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(myPage,queryWrapper);

        BeanUtils.copyProperties(myPage,dtoPage,"records");
        List<OrderDto> dtoList= myPage.getRecords().stream().map(item->{
            OrderDto orderDto=new OrderDto();
            BeanUtils.copyProperties(item,orderDto);
            AddressBook address = addressBookService.getById(item.getAddressBookId());
            orderDto.setAddress(address.getPrivinceName()+address.getCityName()+address.getDetail());
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId,item.getId());
            orderDto.setName(orderDetailService.getOne(wrapper).getName());
            return orderDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(dtoList);
        return R.success(dtoPage);
    }
}
